package cn.kgc.shiro;

import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

import java.util.Arrays;
import java.util.List;

/**
 * @author 课工场
 * @date 2023/11/21
 * @description  用户自定义域对象
 */
public class CustomerRealm  extends AuthorizingRealm {


    //授权方法     当用户访问受限资源时 自动调用
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        System.out.println("--------------doGetAuthorizationInfo--------------------");
        // 获取用户的身份信息
        Object primaryPrincipal = principals.getPrimaryPrincipal();
        System.out.println("primaryPrincipal = " + primaryPrincipal);

        // TODO 根据用户名 查询数据库  判定用户具有哪些权限    RBAC  user  role  user_role
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();

        // simpleAuthorizationInfo.addRole("root");
        List<String> roles = Arrays.asList("admin", "root", "super");
        simpleAuthorizationInfo.addRoles(roles);

        // 添加权限字符串
        List<String> list = Arrays.asList("sys:user:add", "sys:user:delete");
        simpleAuthorizationInfo.addStringPermissions(list);

        return simpleAuthorizationInfo;
    }


    // 认证方法
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("--------------doGetAuthenticationInfo-----------------");
        UsernamePasswordToken  usernamePasswordToken = (UsernamePasswordToken) token;
        String username = usernamePasswordToken.getUsername();
        System.out.println("username = " + username);
        //TODO  查询数据库
        if ("tom".equals(username)){   //  tom   123456
            SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo("tom",
                    "de925b88805731d32dc7ff541684c5a8",
                    ByteSource.Util.bytes("TPMb.h64"),this.getName());
            return  simpleAuthenticationInfo;
        }
        return null;
    }
}
